<?php

namespace app\admin\controller\member;

use app\api\model\Applyrefund;
use app\common\controller\Backend;
use think\Db;
use think\Exception;
use yansongda\pay\Pay;

/**
 * 销售合伙人申请
 *
 * @icon fa fa-circle-o
 */
class Apply extends Backend
{

    /**
     * Applypartner模型对象
     * @var \app\admin\model\Applypartner
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Applypartner;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("auditList", $this->model->getAuditList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->with(['member'])
                ->where($where)
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->with(['member'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            foreach ($list as $row) {


            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    //通过审核
    public function pass()
    {

        $id = $this->request->param('ids');

        $row = $this->model->get($id);
        if (!$row)
            $this->error(__('No Results were found'));


        $member = new \app\api\model\Member();
        $memberItem = $member->where('openid', $row->openid)->find();
        if (empty($memberItem)) {
            return json(['code' => -1, 'msg' => '扫码用户不存在或已删除']);
        }

        Db::startTrans();
        try {
            $memberItem->username = $row->username;
            $memberItem->mobile = $row->mobile;
            $memberItem->agentid = $row->refereeid;
            $memberItem->save();

            $row->audittime = time();
            $row->audit = 1;
            $rews = $row->save();
            if ($rews < 1) {
                return json(['code' => -1, 'msg' => '审核状态失败']);
            }

            Db::commit();
            return json(['code' => 1, 'msg' => 'success']);
        } catch (Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }

    //拒绝通过
    public function reject()
    {
        $id = $this->request->param('ids');

        $row = $this->model->get($id);
        if (!$row) {
            return json(['code' => -1, 'msg' => '申请记录不存在或已删除']);
        }

        if ($row->type == 3) {//事业合伙人推荐,没有支付金额
            $row->audit = 2;    //驳回
            $row->audittime = time();
            $row->status = 2;   //退款
            $rows = $row->save();
            if ($rows < 1) {
                return json(['code' => -1, 'msg' => '驳回失败']);
            }

            return json(['code' => 1, 'msg' => '驳回成功']);
        }

        Db::startTrans();
        try {
            $row->audit = 2;    //驳回
            $row->audittime = time();
            $row->status = 2;   //退款
            $rows = $row->save();
            if ($rows < 1) {
                return json(['code' => -1, 'msg' => '驳回失败']);
            }
            $order = [
                'out_trade_no' => $row->applysn,
                'out_refund_no' => time(),
                'total_fee' => $row->price * 100,
                'refund_fee' => $row->price * 100,
                'refund_desc' => '驳回审核退款',
                'type' => 'miniapp'
            ];

            $config = $this->processConfig('bindPartner');
            Pay::wechat($config)->refund($order);

            $applyRefund = new Applyrefund();
            $applyRefund->refundsn = $row->applysn;
            $applyRefund->price = $row->price;
            $applyRefund->refundtime = time();
            $applyRefund->openid = $row->openid;
            $applyRefund->save();

            if (!$applyRefund->id) {
                return json(['code' => -1, 'msg' => '驳回失败']);
            }

            Db::commit();
            return json(['code' => 1, 'msg' => '驳回成功']);
        } catch (Exception $e) {
            Db::rollback();
            return json(['code' => -1, 'msg' => $e->getMessage()]);
        }

    }

    protected function processConfig($action)
    {
        $baseurl = $this->request->domain();
        $config = [
            'miniapp_id' => Config('wxpay.appid'), // 小程序 APPID
            'mch_id' => Config('wxpay.mch_id'),
            'key' => Config('wxpay.key'),
            'notify_url' => $baseurl . '/api/Payresult/' . $action,//支付回调url
            'cert_client' => './apiclient_cert.pem', // optional，退款等情况时用到(文件放在更目录下)
            'cert_key' => './apiclient_key.pem',// optional，退款等情况时用到
            'log' => [ // optional
                'file' => './logs/wechat.log',
                'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
                'type' => 'single', // optional, 可选 daily.
                'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
            ],
            'http' => [ // optional
                'timeout' => 5.0,
                'connect_timeout' => 5.0,
            ],
        ];
        return $config;
    }

    //退款通知


}
